package com.innovation.chengzhangriji.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.google.gson.JsonElement;
import com.google.zxing.datamatrix.DataMatrixReader;
import com.innovation.chengzhangriji.Baby;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.Discover;
import com.innovation.chengzhangriji.DiscoverPhoto;
import com.innovation.chengzhangriji.DiscoverSaveComment;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.http.DiscoverCommentResponse;
import com.innovation.chengzhangriji.http.DiscoverContentResponse;
import com.innovation.chengzhangriji.http.DiscoverLikeResponse;
import com.innovation.chengzhangriji.http.DiscoverResponse;
import com.innovation.chengzhangriji.http.ResponseHandler;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.ui.widget.CuteToolbar;
import com.innovation.chengzhangriji.ui.widget.DiscoverAdapter;
import com.innovation.chengzhangriji.ui.widget.DiscoverAudioViewHolder;
import com.innovation.chengzhangriji.ui.widget.DiscoverMilestoneViewHolder;
import com.innovation.chengzhangriji.ui.widget.DiscoverPhotoViewHolder;
import com.innovation.chengzhangriji.ui.widget.DiscoverProgressViewHolder;
import com.innovation.chengzhangriji.ui.widget.DiscoverTextViewHolder;
import com.innovation.chengzhangriji.ui.widget.DiscoverVideoViewHolder;
import com.innovation.chengzhangriji.ui.widget.DiscoverViewHolder;
import com.innovation.chengzhangriji.ui.widget.FriendItemDecoration;
import com.innovation.chengzhangriji.util.ChZhRJUtils;
import com.innovation.chengzhangriji.util.FileUtils;
import com.loopj.android.http.FileAsyncHttpResponseHandler;
import com.orhanobut.logger.Logger;

import org.apache.http.Header;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

/**
 * Created by lichuanzhi on 2015/11/25.
 */
public class DiscoverCommentDetailActivity extends BaseActivity implements DiscoverAdapter.Observer, DiscoverAdapter.TextObserver, DiscoverAdapter.PhotoObserver, DiscoverAdapter.AudioObserver, DiscoverAdapter.VideoObserver, DiscoverAdapter.MilestoneObserver, DiscoverAdapter.LikeObserver, DiscoverAdapter.CommentObserver, View.OnClickListener, CuteToolbar.OnClickCuteToolbarListener, View.OnTouchListener {

    private String diaryId;
    private Discover discover;
    private DiscoverAdapter adapter;

    // 当前日记赞的列表
    private ArrayList<DiscoverSaveComment> likeList = new ArrayList<>();

    // 当前日记评论的列表
    private ArrayList<DiscoverSaveComment> commentList = new ArrayList<>();

    // 当前评论的照片列表
    private ArrayList<DiscoverPhoto> photoList = new ArrayList<>();

    // 是否显示音频
    private boolean isAudioShow = false;

    // 是否播放音频
    private boolean isAudioPlay = false;

    // 是否下载音频中
    private boolean isAudioDownloading = false;

    // 音频是否下载成功
    private boolean isAudioDownloadSucceed = false;

    // 媒体播放
    private MediaPlayer player;

    private int positionComment = -1;

    private int positionLayerComment = -1;

    private String targetUuid;

    private String targetName;

    private String targetNickname;

    private String targetUserId;

    private RecyclerView recyclerView;

    private RelativeLayout layout;

    private EditText editComment;

    private LoginInfo loginInfo;

    // 是否已删除
    private boolean isDeleted = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        loginInfo = Config.getLoginInfo(this);
        if (loginInfo == null) {
            tipShow("请重新登录");
            finish();
            return;
        }

        // 查询评论页缓存的日记信息
        diaryId = getIntent().getStringExtra("diaryId");

        // 获取本地日记
        getLocalDiscover();

        // 初始化视图
        setupViews();

        // 联网请求日记信息
        requestDiscover();
    }

    // 获取本地日记
    private void getLocalDiscover() {
        discover = DatabaseManager.getInstance(this).getDiscoverByDiaryId(diaryId, 3);

        // 当日记不存在时
        if(discover == null) {
            if(!Client.isNetworkConnect(this)) {
                tipShow("日记加载失败");
                finish();
                return;
            }
        }
    }

    // 初始化视图
    public void setupViews() {

        setContentView(R.layout.activity_discover_comment_detail);

        CuteToolbar toolbar = (CuteToolbar) findViewById(R.id.toolbar);
        toolbar.setOnClickCuteToolbarListener(this);

        recyclerView = (RecyclerView) findViewById(R.id.recycler);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new FriendItemDecoration());
        recyclerView.setItemAnimator(null);
        recyclerView.setOnTouchListener(this);

        layout = (RelativeLayout) findViewById(R.id.layout_bottom);
        editComment = (EditText) findViewById(R.id.edit_comment);
        ImageView buttonComment = (ImageView) findViewById(R.id.button_comment);
        buttonComment.setOnClickListener(this);

        adapter = new DiscoverAdapter(this);
        adapter.setObserver(this);
        adapter.setTextObserver(this);
        adapter.setPhotoObserver(this);
        adapter.setAudioObserver(this);
        adapter.setVideoObserver(this);
        adapter.setMilestoneObserver(this);
        adapter.setLikeObserver(this);
        adapter.setCommentObserver(this);
        adapter.setEnd(true);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        if(event.getAction() == MotionEvent.ACTION_DOWN) {
            // 隐藏输入法
            InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(recyclerView.getWindowToken(), 0);
            layout.setVisibility(View.INVISIBLE);
        }
        return false;
    }

    // 显示离线数据
    private void showOfflineData() {
        // 没联网时显示或联网请求失败
        commentList.addAll(DatabaseManager.getInstance(this).getDiscoverAllComments(diaryId, 1));
        likeList.addAll(DatabaseManager.getInstance(this).getDiscoverAllComments(diaryId, 2));
        photoList.addAll(DatabaseManager.getInstance(this).getDiscoverPhotos(diaryId));
        recyclerView.setAdapter(adapter);
    }

    // 请求日记信息
    private void requestDiscover() {
        String phone = loginInfo.getPhone();
        String token = loginInfo.getToken().getAccessToken();
        Client.requestSingleDiscover(this, phone, token, diaryId, new ResponseHandler() {

            @Override
            public void onInnovationSuccess(JsonElement value) {
                super.onInnovationSuccess(value);
                Logger.json(value.toString());
                DiscoverResponse response = get(value.toString(), DiscoverResponse.class);
                if (response == null || response.getContent() == null) {
                    // 没有获取到，操作时，提示日记已删除
                    isDeleted = true;
                    showOfflineData();
                    return;
                }
                // 提前下载音频
                if (discover.getType() == 3) {
                    if (TextUtils.isEmpty(discover.getAudioLocalUrl())) {
                        downloadAudio(0);
                    } else {
                        File file = new File(discover.getAudioLocalUrl());
                        if (!file.exists()) {
                            downloadAudio(0);
                        }
                    }
                }
                // 保存日记到本地数据库
                storeDiscoverToLocal(response.getContent());
                // 保存日记的评论到本地数据库
                storeDiscoverCommentToLocal(response);
                // 更新适配器
                recyclerView.setAdapter(adapter);
                // 获取本地日记
                getLocalDiscover();
                showOfflineData();
                adapter.notifyItemChanged(0);
            }

            @Override
            public void onInnovationError() {
                super.onInnovationError();
                showOfflineData();
            }

            @Override
            public void onInnovationExceptionFinish() {
                super.onInnovationExceptionFinish();
                showOfflineData();
            }

            @Override
            public void onInnovationFailure(String msg) {
                super.onInnovationFailure(msg);
                showOfflineData();
            }
        }, new Client.NetworkUnavailableListener() {
            @Override
            public void networkUnavailable() {
                showOfflineData();
            }
        });
    }

    // 创建 日记 对象
    private Discover setupDiscover(DiscoverContentResponse response) {
        Discover discover = new Discover();
        discover.setAudio(response.getAudio());
        discover.setUserHeadUrl(response.getHeadUrl());
        discover.setBabyID(response.getBabyId());
        discover.setBabyName(response.getBabyName());
        discover.setCreateTS(response.getCreateTS());
        discover.setDuration(response.getMediaLength());
        discover.setGrowthStageID(response.getState());
        discover.setMemberName(response.getName());
        discover.setMilestone(response.getMilestone());
        discover.setScreenshot(response.getScreenshot());
        discover.setText(response.getText());
        discover.setTheme(response.getTheme());
        discover.setNickName(response.getNickName());
        discover.setType(response.getType());
        // 接口没返回 UserId，不在更新 UserID
        discover.setUserID(response.getUserId());
        discover.setVideo(response.getVideo());
        discover.setDiaryFrom(3);
        discover.setDiaryID(response.getDiaryId());
        discover.setBabyHeadUrl(response.getBabyHeadUrl());
        discover.setIsDelete(response.getState() == 0);
        return discover;
    }

    // 添加普通评论
    private void addComment(DiscoverCommentResponse[] responses, ArrayList<DiscoverSaveComment> comments, int from) {
        if(responses == null || responses.length == 0) return;
        for(int i = 0; i < responses.length; i++) {
            DiscoverSaveComment comment = new DiscoverSaveComment();
            comment.setCommentType(1);
            comment.setContent(responses[i].getComment());
            comment.setCreateTS(responses[i].getTs());
            comment.setDiaryID(responses[i].getDiaryId());
            comment.setOperationState(responses[i].getCommentState());
            comment.setUserID(responses[i].getCommentId());
            comment.setReplyUserID(responses[i].getTargetUserId());
            comment.setReplyNickname(responses[i].getTargetNickname());
            comment.setUserNickname(responses[i].getCommentNickname());
            comment.setReplyIdentity(responses[i].getTargetId());
            comment.setUserHeadUrl(responses[i].getCommentHeadUrl());
            comment.setIsNew(true);
            comment.setMemberName(responses[i].getCommentName());
            comment.setReplyMemberName(responses[i].getTargetName());
            comment.setIsLocal(false);
            if(from == 1) {
                // 只有当为最新评论时，才记录所属用户的信息
                comment.setBelongUserId(loginInfo.getUserID());
            }
            comment.setIdentity(responses[i].getId());
            comment.setFrom(from); // 1：最新评论 2：日记本身评论
            comments.add(comment);
        }
    }

    // 添加点赞评论
    private void addComment(DiscoverLikeResponse[] responses, ArrayList<DiscoverSaveComment> comments, int from) {
        if(responses == null || responses.length == 0) return;
        for(int i = 0; i < responses.length; i++) {
            DiscoverSaveComment comment = new DiscoverSaveComment();
            comment.setCommentType(2);
            comment.setCreateTS(responses[i].getTs());
            comment.setDiaryID(responses[i].getDiaryId());
            comment.setOperationState(responses[i].getLikeState());
            comment.setUserID(responses[i].getLikeId());
            comment.setUserHeadUrl(responses[i].getLikeHeadUrl());
            comment.setUserNickname(responses[i].getLikeNickname());
            comment.setIsNew(true);
            comment.setMemberName(responses[i].getLikeName());
            comment.setIsLocal(false);
            if(from == 1) {
                // 只有当为最新评论时，才记录所属用户的信息
                comment.setBelongUserId(loginInfo.getUserID());
            }
            comment.setIdentity(responses[i].getId());
            comment.setFrom(from); // 1：最新评论 2：日记本身评论
            comments.add(comment);
        }
    }

    // 保存日记到本地数据库
    private void storeDiscoverToLocal(DiscoverContentResponse response) {
        if(response != null) {
            Discover discover = setupDiscover(response);
            DatabaseManager.getInstance(this).insertOrReplaceDiscover(discover, response.getPhotos());
        }
    }

    // 保存日记的评论到本地的数据库
    private void storeDiscoverCommentToLocal(DiscoverResponse response) {
        // 删除日记之前的评论
        DatabaseManager.getInstance(this).deleteDiscoverComments(response.getContent().getDiaryId());

        ArrayList<DiscoverSaveComment> comments = new ArrayList<>();
        if(response.getComment() != null) {
            addComment(response.getComment(), comments, 2);
        }
        if(response.getLike() != null) {
            addComment(response.getLike(), comments, 2);
        }
        DatabaseManager.getInstance(this).insertOrReplaceDiscoverSaveCommentInTx(comments);
    }

    @Override
    public int length() {
        return 1;
    }

    @Override
    public int type(int position) {
        if (discover.getType() == 1) {
            if (TextUtils.isEmpty(discover.getMilestone())) {
                return 0;
            } else {
                return 4;
            }
        }
        return discover.getType() - 1;
    }

    @Override
    public String userName(int position) {
        return discover.getMemberName();
    }

    @Override
    public String userUrl(int position) {
        return discover.getUserHeadUrl();
    }

    @Override
    public String babyName(int position) {
        // return discover.getBabyName();
        Baby baby = DatabaseManager.getInstance(this).queryBaby(discover.getBabyID());
        return ChZhRJUtils.getText(baby.getNoteName(), "来自" + " " + baby.getName() + "的成长日记");
    }

    @Override
    public String babyUrl(int position) {
        Baby baby = DatabaseManager.getInstance(this).queryBaby(discover.getBabyID());
        // return discover.getBabyHeadUrl();
        return baby.getImageUrl();
    }

    @Override
    public int babySex(int position) {
        return DatabaseManager.getInstance(this).queryBaby(discover.getBabyID()).getGender();
    }

    @Override
    public String time(int position) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.SIMPLIFIED_CHINESE);
        Date date = new Date(discover.getCreateTS());
        return sf.format(date);
    }

    @Override
    public boolean showBottom(int position) {
        return showLike(position) || showComment(position);
    }

    @Override
    public String text(int position) {
        return discover.getText();
    }

    @Override
    public void onClickPhoto(int position1, int position2) {
        Intent intent = new Intent(this, DiscoverGalleryActivity.class);
        intent.putExtra("photoUrls", photoUrl(position1));
        intent.putExtra("index", position2);
        startActivity(intent);
    }

    @Override
    public String photoLabel(int position) {
        return discover.getTheme();
    }

    @Override
    public String photoContent(int position) {
        return discover.getText();
    }

    @Override
    public String[] photoUrl(int position) {
        String[] photos = new String[photoList.size()];
        for(int i = 0; i < photoList.size(); i++) {
            photos[i] = photoList.get(i).getUrl();
        }
        return photos;
    }

    @Override
    public void onClickAudio(int position) {
        if (!isAudioPlay) {
            isAudioPlay = true;
            adapter.notifyItemChanged(position);
            // 开始播放
            playAudio(discover.getAudioLocalUrl());
        } else {
            isAudioPlay = false;
            adapter.notifyItemChanged(position);
            // 停止播放
            stopPlayback();
        }
    }

    // 播放音频
    private void playAudio(final String path) {
        player = new MediaPlayer();
        try {
            if(path == null) {
                player.setDataSource(discover.getAudio());
            } else {
                player.setDataSource(path);
            }
            player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    isAudioPlay = false;
                    adapter.notifyItemChanged(0);
                    stopPlayback();
                }
            });
            player.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    stopPlayback();
                    return true;
                }
            });
            player.prepare();
            player.start();
        } catch (IOException e) {
            e.printStackTrace();
            stopPlayback();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopPlayback();
    }

    // 停止播放
    private void stopPlayback() {
        if (player == null) // we were not in playback
            return;
        player.stop();
        player.release();
        player = null;
    }

    @Override
    public int audioLength(int position) {
        return discover.getDuration();
    }

    @Override
    public boolean audioPlay(int position) {
        return isAudioPlay;
    }

    @Override
    public boolean audioShow(int position) {
        return isAudioShow;
    }

    @Override
    public boolean audioDownloading(int position) {
        return isAudioDownloading;
    }

    @Override
    public boolean audioDownloadSucceed(int position) {
        return isAudioDownloadSucceed;
    }

    // 下载音频
    @Override
    public void downloadAudio(final int position) {
        String audioUrl = discover.getAudio();
        if(audioUrl == null) {
            return;
        }
        int start = audioUrl.indexOf(Config.AUDIO);
        if(start == -1) {
            return;
        }
        String subUrl = audioUrl.substring(start);
        File file = new File(getExternalCacheDir(), String.valueOf(subUrl.hashCode()));
        if (file.exists()) {
            isAudioDownloadSucceed = true;
            isAudioShow = true;
            discover.setAudioLocalUrl(file.getPath());
            final Handler handler = new Handler();
            final Runnable r = new Runnable() {
                public void run() {
                    adapter.notifyItemChanged(position);
                }
            };
            handler.post(r);
        } else {
            isAudioDownloading = true;
            Client.downloadFile(this, audioUrl, new FileAsyncHttpResponseHandler(file) {
                @Override
                public void onFailure(int statusCode, Header[] headers, Throwable throwable, File file) {
                    isAudioDownloading = false;
                    adapter.notifyItemChanged(position);
                }

                @Override
                public void onSuccess(int statusCode, Header[] headers, File file) {
                    isAudioDownloading = false;
                    DatabaseManager.getInstance(DiscoverCommentDetailActivity.this).updateDiscoverAudioLocalPath(file.getAbsolutePath(), diaryId);
                    adapter.notifyItemChanged(position);
                }
            }, new Client.NetworkUnavailableListener() {
                @Override
                public void networkUnavailable() {
                    isAudioDownloading = false;
                    adapter.notifyItemChanged(position);
                }
            });
        }
    }

    @Override
    public void onClickVideo(int position) {
        Intent intent = new Intent(this, DiscoverVideoActivity.class);
        intent.putExtra("videoUrl", discover.getVideo());
        startActivity(intent);
    }

    @Override
    public String thumbnailUrl(int position) {
        return discover.getScreenshot();
    }

    @Override
    public String milestone(int position) {
        return discover.getMilestone();
    }

    @Override
    public void onClickLike(int position) {
//        if(!Client.isNetworkConnect(this)) {
//            tipShow("日记暂不支持离线评论");
//            return;
//        }
        if(isDeleted) {
            tipShow("日记已删除，不能进行操作");
            return;
        }
        requestLike(position);
    }

    private void requestLike(final int position) {
        String phone = loginInfo.getPhone();
        String token = loginInfo.getToken().getAccessToken();
        String userId = loginInfo.getUserID();
        String nickname = loginInfo.getName();
        Baby baby = DatabaseManager.getInstance(this).queryBaby(discover.getBabyID());
        if (baby == null) {
            tipShow("已取消关注,不可以操作");
            return;
        }
        String name = baby.getParentName();

        String uuid = null;
        int likeIndex = -1;
        boolean like = true;
        if (likeList == null || likeList.size() == 0) {
            uuid = UUID.randomUUID().toString();
            uuid = uuid.replaceAll("-", "");
        } else {
            for (int i = 0; i < likeList.size(); i++) {
                if (userId.equals(likeList.get(i).getUserID()) && likeList.get(i).getOperationState() == 1) {
                    uuid = likeList.get(i).getIdentity();
                    likeIndex = i;
                    like = false;
                    break;
                }
            }
            if (like) {
                uuid = UUID.randomUUID().toString();
                uuid = uuid.replaceAll("-", "");
            }
        }

        final DiscoverSaveComment comment = new DiscoverSaveComment();
        comment.setCommentType(2);
        comment.setUserHeadUrl(loginInfo.getUrl());
        comment.setIsNew(false);
        comment.setDiaryID(diaryId);
        comment.setIdentity(uuid);
        comment.setUserID(userId);
        comment.setOperationState(1);
        comment.setMemberName(name);
        comment.setUserNickname(nickname);
        comment.setFrom(2);
        comment.setCreateTS(System.currentTimeMillis());

        if (like) {
            likeList.add(comment);          // 点赞

            adapter.notifyItemChanged(position);

            Client.requestLike(this, phone, token, diaryId, uuid, new ResponseHandler() {

                @Override
                public void onInnovationSuccess(JsonElement value) {
                    super.onInnovationSuccess(value);
                    // 有网的时候存储到本地
                    comment.setIsLocal(false);
                    DatabaseManager.getInstance(DiscoverCommentDetailActivity.this).insertOrReplaceDiscoverSaveComment(comment);
                }
            }, new Client.NetworkUnavailableListener() {

                @Override
                public void networkUnavailable() {
                    // 离线时，存储离线评论，待有网的时候处理
                    comment.setIsLocal(true);
                    DatabaseManager.getInstance(DiscoverCommentDetailActivity.this).insertOrReplaceDiscoverSaveComment(comment);
                }
            });
        } else {

            if (likeIndex != -1) {
                likeList.remove(likeIndex); // 取消点赞
                adapter.notifyItemChanged(position);
            }

            final String commentId = uuid;
            Client.requestUnLike(this, phone, token, diaryId, uuid, new ResponseHandler() {

                @Override
                public void onInnovationSuccess(JsonElement value) {
                    super.onInnovationSuccess(value);
                    DatabaseManager.getInstance(DiscoverCommentDetailActivity.this).deleteComment(commentId);
                }
            }, new Client.NetworkUnavailableListener() {

                @Override
                public void networkUnavailable() {
                    // 离线时，存储离线评论，待有网的时候处理
                    comment.setOperationState(0);
                    comment.setIsLocal(true);
                    DatabaseManager.getInstance(DiscoverCommentDetailActivity.this).insertOrReplaceDiscoverSaveComment(comment);
                }
            });
        }
    }

    private void requestComment() {
//        if(!Client.isNetworkConnect(this)) {
//            hideCommentLayout();
//            tipShow("日记暂不支持离线评论");
//            return;
//        }
        if(isDeleted) {
            hideCommentLayout();
            tipShow("日记已删除，不能进行操作");
            return;
        }
        if (TextUtils.isEmpty(editComment.getText())) {
            return;
        }
        String phone = loginInfo.getPhone();
        String token = loginInfo.getToken().getAccessToken();
        String userId = loginInfo.getUserID();
        Baby baby = DatabaseManager.getInstance(this).queryBaby(discover.getBabyID());
        if (baby == null) {
            tipShow("已取消关注,不可以操作");
            return;
        }
        String name = baby.getParentName();
        String nickname = loginInfo.getName();
        String diaryId = discover.getDiaryID();
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replaceAll("-", "");
        String comment = editComment.getText().toString();

        final DiscoverSaveComment saveComment = new DiscoverSaveComment();
        saveComment.setCommentType(1);
        saveComment.setDiaryID(diaryId);
        saveComment.setIdentity(uuid);
        saveComment.setUserID(userId);
        saveComment.setUserHeadUrl(loginInfo.getUrl());
        saveComment.setOperationState(1);
        saveComment.setMemberName(name);
        saveComment.setUserNickname(nickname);
        saveComment.setContent(comment);
        saveComment.setCreateTS(System.currentTimeMillis());

        if (positionLayerComment != -1) {
            saveComment.setReplyIdentity(targetUuid);
            saveComment.setReplyMemberName(targetName);
            saveComment.setReplyNickname(targetNickname);
            saveComment.setReplyUserID(targetUserId);
        }
        saveComment.setIsNew(false);
        saveComment.setFrom(2);
        commentList.add(saveComment);

        adapter.notifyItemChanged(positionComment);

        hideCommentLayout();

        // Client.requestComment(this, phone, token, diaryId, uuid, comment, targetUuid, new ResponseHandler(), networkUnavailableSampleImpl());
        Client.requestComment(this, phone, token, diaryId, uuid, comment, targetUuid, new ResponseHandler() {

            @Override
            public void onInnovationSuccess(JsonElement value) {
                super.onInnovationSuccess(value);
                // 将评论保存到本地
                saveComment.setIsLocal(false);
                DatabaseManager.getInstance(DiscoverCommentDetailActivity.this).insertOrReplaceDiscoverSaveComment(saveComment);
            }
        }, new Client.NetworkUnavailableListener() {

            @Override
            public void networkUnavailable() {
                // 离线时，存储离线评论，待有网的时候处理
                saveComment.setIsLocal(true);
                DatabaseManager.getInstance(DiscoverCommentDetailActivity.this).insertOrReplaceDiscoverSaveComment(saveComment);
            }
        });
    }

    // 隐藏评论框
    private void hideCommentLayout() {
        layout.setVisibility(View.INVISIBLE);
        editComment.setText(null);
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    private void deleteDialog(final DiscoverSaveComment comment) {
        new AlertDialog.Builder(this).setTitle("删除该条评论?").setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                commentList.remove(comment);
                adapter.notifyItemChanged(positionComment);
                requestDeleteComment(comment);
            }
        }).setNegativeButton("取消", null).show();
    }

    private void requestDeleteComment(final DiscoverSaveComment comment) {
        String phone = loginInfo.getPhone();
        String token = loginInfo.getToken().getAccessToken();
        Client.requestDeleteComment(this, phone, token, comment.getIdentity(), new ResponseHandler() {
            @Override
            public void onInnovationSuccess(JsonElement value) {
                super.onInnovationSuccess(value);
                DatabaseManager.getInstance(DiscoverCommentDetailActivity.this).deleteComment(comment.getIdentity());
            }
        }, new Client.NetworkUnavailableListener () {

            @Override
            public void networkUnavailable() {
                comment.setOperationState(0);
                comment.setIsLocal(true);
                DatabaseManager.getInstance(DiscoverCommentDetailActivity.this).insertOrReplaceDiscoverSaveComment(comment);
            }
        });
    }

    @Override
    public boolean isLike(int position) {
        if (likeList == null || likeList.size() == 0) {
            return false;
        }
        String userId = loginInfo.getUserID();
        for (int i = 0; i < likeList.size(); i++) {
            if (userId.equals(likeList.get(i).getUserID())) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int likeNumber(int position) {
        return likeList.size();
    }

    @Override
    public boolean showLike(int position) {
        return likeNumber(position) > 0;
    }

    @Override
    public ArrayList<String> likeList(int position) {
        if(likeNumber(position) == 0) {
            return null;
        }
        ArrayList<String> stringArrayList = new ArrayList<String>();
        for (int i = 0; i < likeList.size(); i++) {
            stringArrayList.add(likeList.get(i).getMemberName());
        }
        return stringArrayList;
    }

    @Override
    public void onClickComment(int position) {
//        if(!Client.isNetworkConnect(this)) {
//            tipShow("日记暂不支持离线评论");
//            return;
//        }
        if(isDeleted) {
            tipShow("日记已删除，不能进行操作");
            return;
        }
        positionComment = position;
        positionLayerComment = -1;
        targetUuid = "";
        targetName = "";
        targetNickname = "";
        targetUserId = "";
        layout.setVisibility(View.VISIBLE);
        editComment.requestFocus();
        editComment.setHint(null);
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
    }

    @Override
    public void onClickComment(int position1, int position2) {
        positionComment = position1;
        positionLayerComment = position2;

        String userId = loginInfo.getUserID();
        int num = 0;
        for (int i = 0; i < commentList.size(); i++) {
            if (positionLayerComment == num) {
                if (userId.equals(commentList.get(i).getUserID())) {
                    deleteDialog(commentList.get(i));
                    return;
                } else {
                    targetUuid = commentList.get(i).getIdentity();
                    targetName = commentList.get(i).getMemberName();
                    targetNickname = commentList.get(i).getUserNickname();
                    targetUserId = commentList.get(i).getUserID();
                    commentList.get(i).getUserID();
                    break;
                }
            }
            num++;
        }
        layout.setVisibility(View.VISIBLE);
        editComment.requestFocus();
        editComment.setHint("回复" + targetName);
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
    }

    @Override
    public int commentNumber(int position) {
        return commentList.size();
    }

    @Override
    public boolean showComment(int position) {
        return commentNumber(position) > 0;
    }

    @Override
    public ArrayList<DiscoverAdapter.CommentModel> commentList(int position) {
        if (commentNumber(position) == 0) {
            return null;
        }
        ArrayList<DiscoverAdapter.CommentModel> commentArrayList = new ArrayList<DiscoverAdapter.CommentModel>();
        for (int i = 0; i < commentList.size(); i++) {
            DiscoverAdapter.CommentModel model = new DiscoverAdapter.CommentModel();
            model.setUserName1(commentList.get(i).getMemberName());
            model.setUserName2(commentList.get(i).getReplyMemberName());
            model.setContent(commentList.get(i).getContent());
            commentArrayList.add(model);
        }
        return commentArrayList;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_comment:
                requestComment();
                break;
        }
    }

    @Override
    public void onClickLeft() {
        finish();
    }

    @Override
    public void onClickRight() {

    }
}
